import React from 'react';
import PageNavbar from './PageNavbar';
import BestGenreRow from './BestGenreRow';
import '../style/BestGenres.css';
import 'bootstrap/dist/css/bootstrap.min.css';

export default class BestGenre extends React.Component {
	constructor(props) {
		super(props);

		this.state = {
			selectedDecade: "",
			decades: [],
			genres: []
		};
		this.selectChange = this.handleChange.bind(this);
		//this.submitChange = this.submitDecade.bind(this)
	}

	handleChange(e) {
		
		let optionDom = e.target.options[e.target.selectedIndex]
        let v = optionDom.value
		this.setState({
			selectedDecade: v
		})
	}
	/* ---- Q3a (Best Genres) ---- */
	async componentDidMount() {
		let res = await fetch("http://localhost:8081/decades")
		let dedcadesList = await res.json()
		let decadesDivs = dedcadesList.map((decadesResult, i) =>
		<option value ={decadesResult.decade}>{decadesResult.decade}</option>
		);
	
		this.setState({
			decades:decadesDivs
		});
	}



	/* ---- Q3b (Best Genres) ---- */
	async submitDecade() {
		let selectedDecade = this.state.selectedDecade
		let res = await fetch("http://localhost:8081/decades/" + selectedDecade)
		let genreList = await res.json()
		this.setState({
			genres: genreList
		});
	}

  	
	render() {

		return (
			<div className="BestGenres">
				<PageNavbar active="bestgenres" />

				<div className="container bestgenres-container">
			      <div className="jumbotron">
			        <div className="h5">Best Genres</div>

			        <div className="years-container">
			          <div className="dropdown-container">
			            <select value={this.state.selectedDecade} onChange={this.selectChange} className="dropdown" id="decadesDropdown">
			            	<option select value> -- select an option -- </option>
			            	{this.state.decades}
			            </select>
			            <button className="submit-btn" id="decadesSubmitBtn" onClick={async () => await this.submitDecade()}>Submit</button>
			          </div>
			        </div>
			      </div>
			      <div className="jumbotron">
			        <div className="movies-container">
			          <div className="movie">
			            <div className="header"><strong>Genre</strong></div>
			            <div className="header"><strong>Average Rating</strong></div>
			          </div>
			          <div className="movies-container" id="results">
			            {
							this.state.genres.map((genreResult) =>
							<BestGenreRow genre = {genreResult.genre} avg_rating ={genreResult.avgRating}/>)
						}
			          </div>
			        </div>
			      </div>
			    </div>
			</div>
		);
	}
}
